import axios from "axios";
import { clearCache, getCache } from "@/utils/cache";
import router from "@/router";
import { message } from "ant-design-vue";

export function request(config) {
  const instance = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 5000
  });

  instance.interceptors.request.use(
    config => {
      const token = getCache("token");
      const current_role = getCache("role")?.id;
      if (token) {
        config.headers.Authorization = token;
        config.headers.currentRole = current_role;
      }
      return config;
    },
    error => {
      message.error("请求失败");
    }
  );

  // 响应
  instance.interceptors.response.use(
    res => {
      return res.data.data;
    },
    error => {
      if (error.response.status === 401) {
        message.error(error.response.data.detail);
        clearCache();
        router.push("/login");
      }
    }
  );

  // 发送请求
  return instance(config);
}
